import path from 'path'
import { git } from './git'
import { twoGroupBy } from '../lib/array/two-group-by'

export type Change = {
  type: string
  path: string
}

const allChanges = (): Change[] =>
  git
    .shortStatus()
    .split('\n')
    .filter(n => !!n)
    .map((one): Change => {
      return {
        type: one.slice(0, 2),
        path: one.slice(3),
      }
    })

const groupStageOrNotStaged = twoGroupBy<Change>(({ type }) => {
  const a = type[0]
  return a !== '?' && a !== ' '
})

export class GitChanges {
  static fromShortStatus() {
    return new GitChanges(allChanges())
  }
  static divideByStaged(a: GitChanges) {
    return groupStageOrNotStaged(a.get()).map((s, i) => {
      return new GitChanges(s.map(one => ({ ...one, type: one.type[i] })))
    })
  }
  constructor(private changes: Change[]) {}
  get() {
    return this.changes
  }
  getFiles() {
    return this.changes.map(one => one.path)
  }
  getTypes() {
    return this.changes.map(one => one.type)
  }
  count() {
    return this.changes.length
  }
  toFileListString() {
    const v = this.getFiles()
      .map(one => path.basename(one))
      .join(',')

    return `<${v}>`
  }
}
